package com.scalar.chiptrack.operations.process.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.ArrayList;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.util.LabelValueBean;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.operations.process.forms.ProductSubstitutablesForm;
import com.scalar.chiptrack.operations.process.dao.ProductSubstitutablesDAO;


public final class ProductSubstitutablesAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/productSubstitutables.do" ;
    public ActionForward execute ( ActionMapping mapping , ActionForm form ,
                                   HttpServletRequest request , HttpServletResponse response ) throws Exception
    {
        HashMap<String, String> info = new HashMap<String, String>();
        HashMap<String, String> errors = new HashMap<String, String>();
        DBTransaction dbTransaction = null;

        HttpSession session = request.getSession(true);
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        String action = request.getParameter ( "action" );
        if ( action == null )
        {
            action = "";
        }
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.PRODUCT_SUBSTITUTABLES, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        ProductSubstitutablesForm productSubstitutablesForm = ( ProductSubstitutablesForm ) form;

        ArrayList<LabelValueBean> productList = new ArrayList<LabelValueBean>();                        //represents products
        ArrayList<LabelValueBean> substitutableProductList = new ArrayList<LabelValueBean>();           //represents Substitutables products for the selected Product
        ArrayList<LabelValueBean> selectedSubstitutableProductList = new ArrayList<LabelValueBean>();   //represents Substituted Products for the selected Product


        if ( action.trim().length() == 0  )
        {                                          //This block will be execute when we click on the "Product Substitutable" Link in Operations.
            productSubstitutablesForm.setSelectedProduct("");

            request.setAttribute("productList", productList);
            request.setAttribute("substitutableProductList", substitutableProductList);
            request.setAttribute("selectedSubstitutableProductList", selectedSubstitutableProductList);
            return ( mapping.findForward ( "success" ) );
        }
        else if ( action.equals( "Products" ) )    //This block will be execute when we select ProductType.
        {
            String productType = productSubstitutablesForm.getProductType() ;
            productList = ProductSubstitutablesDAO.getProducts( productType );

            request.setAttribute("productList", productList);
            request.setAttribute("substitutableProductList", substitutableProductList);
            request.setAttribute("selectedSubstitutableProductList", selectedSubstitutableProductList);
        }
        else if ( action.equals("Substitutes"))
        {                                           //This block will be execute when we select Product.
            int selectedProductProecssStepID = -1;
            String productType = productSubstitutablesForm.getProductType() ;
            try
            {
                selectedProductProecssStepID = Integer.parseInt(productSubstitutablesForm.getSelectedProduct());
            }
            catch( NumberFormatException nfe)
            {
                selectedProductProecssStepID = -1;
            }
            productList = ProductSubstitutablesDAO.getProducts( productType );

            substitutableProductList = ProductSubstitutablesDAO.getSubustitutableProducts(productType, selectedProductProecssStepID);
            selectedSubstitutableProductList = ProductSubstitutablesDAO.retriveSubstitutableProcessStepIds ( null , productSubstitutablesForm.getSelectedProduct() );

            request.setAttribute("productList", productList);
            request.setAttribute("substitutableProductList", substitutableProductList);
            request.setAttribute("selectedSubstitutableProductList", selectedSubstitutableProductList);
        }
        else if ( action.equals("save"))
        {                                           //This block will be execute when we save the Product Substituables.

            boolean isSuccess = false;
            try
            {
                dbTransaction = DBTransaction.getInstance();
                if( dbTransaction != null )
                {
                    dbTransaction.begin();
                }

                isSuccess = ProductSubstitutablesDAO.insertSubstitutableProcessStepId( dbTransaction , productSubstitutablesForm , true );
                info.put ("Product Substitutables have been saved successfully", null);
                request.setAttribute(SessionKeys.INFO_MESSAGES, info);
            }
            catch (Exception e) {
                errors.put ("Unable to save Substitute Products into Data Base", null);
                request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);

                System.out.println ("Exception while storing Substitute Products.... ");
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    if (isSuccess == true) {
                        dbTransaction.commit();
                    }else{
                        dbTransaction.rollback();
                    }
                }
                catch (DBXException e)
                {
                    e.printStackTrace();
                }
            }

            String productType = productSubstitutablesForm.getProductType() ;
            int selectedProductProecssStepID = Integer.parseInt(productSubstitutablesForm.getSelectedProduct());
            productList = ProductSubstitutablesDAO.getProducts( productType );

            substitutableProductList = ProductSubstitutablesDAO.getSubustitutableProducts(productType, selectedProductProecssStepID);
            selectedSubstitutableProductList = ProductSubstitutablesDAO.retriveSubstitutableProcessStepIds ( null , productSubstitutablesForm.getSelectedProduct() );

            productSubstitutablesForm.setSelectedSubstitutableProducts( null );
            request.setAttribute("productList", productList);
            request.setAttribute("substitutableProductList", substitutableProductList);
            request.setAttribute("selectedSubstitutableProductList", selectedSubstitutableProductList);
        }

        return ( mapping.findForward ( "success" ) );
    }

}